package com.mobile_fault_detector.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mobile_fault_detector.entity.DialogSession;
import com.mobile_fault_detector.mapper.IDialogSessionMapper;
import com.mobile_fault_detector.service.IDialogSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 对话会话服务实现类
 */
@Slf4j
@Service
public class DialogSessionServiceImpl implements IDialogSessionService {

    private final IDialogSessionMapper dialogSessionMapper;

    @Autowired
    public DialogSessionServiceImpl(IDialogSessionMapper dialogSessionMapper) {
        this.dialogSessionMapper = dialogSessionMapper;
    }

    @Override
    public DialogSession createSession(DialogSession dialogSession) {
        log.info("创建会话: {}", dialogSession);
        // 设置默认状态为进行中
        if (dialogSession.getSessionStatus() == null) {
            dialogSession.setSessionStatus(0);
        }
        dialogSessionMapper.insert(dialogSession);
        return dialogSession;
    }

    @Override
    public DialogSession getSessionById(Long sessionId) {
        log.info("根据ID查询会话信息: {}", sessionId);
        return dialogSessionMapper.selectById(sessionId);
    }

    @Override
    public List<DialogSession> getSessionsByUserId(Long userId) {
        log.info("根据用户ID查询会话列表: {}", userId);
        LambdaQueryWrapper<DialogSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DialogSession::getUserId, userId)
                .orderByDesc(DialogSession::getStartTime);
        return dialogSessionMapper.selectList(queryWrapper);
    }

    @Override
    public DialogSession updateSessionStatus(Long sessionId, Integer status) {
        log.info("更新会话状态, 会话ID: {}, 状态: {}", sessionId, status);
        DialogSession dialogSession = dialogSessionMapper.selectById(sessionId);
        if (dialogSession != null) {
            dialogSession.setSessionStatus(status);
            dialogSessionMapper.updateById(dialogSession);
        }
        return dialogSession;
    }

    @Override
    public DialogSession endSession(Long sessionId) {
        log.info("结束会话, 会话ID: {}", sessionId);
        DialogSession dialogSession = dialogSessionMapper.selectById(sessionId);
        if (dialogSession != null) {
            dialogSession.setSessionStatus(1); // 设置为已结束
            dialogSession.setEndTime(LocalDateTime.now()); // 设置结束时间
            dialogSessionMapper.updateById(dialogSession);
        }
        return dialogSession;
    }
}